package com.party.admin.web.controller.gatherInfo;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.admin.biz.circle.CircleBizNewService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.gatherInfo.ItineraryBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.gatherInfo.GatherInfoProjectOutput;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.circle.CircleMemberTag;
import com.party.core.model.circle.CircleTag;
import com.party.core.model.competition.CompetitionBusiness;
import com.party.core.model.competition.CompetitionProject;
import com.party.core.model.gatherInfo.GatherInfoGroup;
import com.party.core.model.gatherInfo.GatherInfoMember;
import com.party.core.model.gatherInfo.GatherInfoProject;
import com.party.core.service.circle.ICircleMemberTagService;
import com.party.core.service.circle.ICircleTagService;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.circle.biz.CircleMemberBizService;
import com.party.core.service.competition.ICompetitionBusinessService;
import com.party.core.service.competition.ICompetitionProjectService;
import com.party.core.service.competition.biz.CompetitionProjectBizService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.gatherInfo.IGatherInfoGroupService;
import com.party.core.service.gatherInfo.IGatherInfoMemberService;
import com.party.core.service.gatherInfo.IGatherInfoProjectService;
import com.party.core.service.member.IMemberAdministratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 人员信息采集项目
 *
 * @author Administrator
 */
@Controller
@RequestMapping("gatherInfo/project")
public class GatherInfoProjectController {

    @Autowired
    private IGatherInfoProjectService gatherInfoProjectService;
    @Autowired
    private IGatherInfoGroupService gatherInfoGroupService;
    @Autowired
    private IGatherInfoMemberService gatherInfoMemberService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CompetitionProjectBizService competitionProjectBizService;
    @Autowired
    private ICompetitionProjectService competitionProjectService;
    @Autowired
    private ICompetitionBusinessService competitionBusinessService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private CircleMemberBizService circleMemberBizService;
    @Autowired
    private CircleBizService circleBizService;
    @Autowired
    private ICircleTagService circleTagService;
    @Autowired
    private ICircleMemberTagService circleMemberTagService;
    @Autowired
    private ItineraryBizService itineraryBizService;
    @Autowired
    private CircleBizNewService circleBizNewService;
    @Autowired
    private IMemberAdministratorService memberAdministratorService;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 列表
     *
     * @param page
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(Page page, GatherInfoProject project, CommonInput commonInput) {
        page.setLimit(15);
        project.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        ModelAndView mv = new ModelAndView("gatherInfo/projectList");
        Map<String, Object> param = CommonInput.appendParams(commonInput);

        Map<String, Object> params = RealmUtils.getMemberAdministrator(param,memberAdministratorService);

        List<GatherInfoProject> memberInfoProjects = gatherInfoProjectService.webListPage(project, params, page);
        List<GatherInfoProjectOutput> outputs = LangUtils.transform(memberInfoProjects, input -> {
            GatherInfoProjectOutput output = GatherInfoProjectOutput.transform(input);
            int totalNum = gatherInfoMemberService.getCountByProject(input.getId());
            output.setTotalNum(totalNum);

            GatherInfoGroup t = new GatherInfoGroup();
            t.setProjectId(input.getId());
            List<GatherInfoGroup> groups = gatherInfoGroupService.list(t);
            output.setGroupNum(groups.size());

            String filePath = fileBizService.getUploadCIPath(input.getCreateBy(), "gatherInfo");
            // 活动二维码
            String baseFileName = "base_" + input.getId();
            String baseQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + baseFileName);
            output.setBaseQrCodeUrl(baseQrCodeUrl);

            String insuranceFileName = "insurance_" + input.getId();
            String insuranceQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + insuranceFileName);
            output.setInsuranceQrCodeUrl(insuranceQrCodeUrl);

            String itineraryFileName = "itinerary_" + input.getId();
            String itineraryQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + itineraryFileName);
            output.setItineraryQrCodeUrl(itineraryQrCodeUrl);
            return output;
        });

        mv.addObject("projectList", outputs);
        mv.addObject("input", commonInput);
        mv.addObject("project", project);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 创建圈子
     *
     * @param infoId
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "createCircle")
    public AjaxResult createCircle(String infoId, String type) {
        try {
            GatherInfoMember memberInfo = new GatherInfoMember();
            memberInfo.setProjectId(infoId);
            GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(infoId);
            if (null == type) {
                type = "2";
            }
            //信息收集项目下的会员
            GatherInfoMember gatherInfoMember = new GatherInfoMember();
            GatherInfoGroup gatherInfoGroup = new GatherInfoGroup();
            gatherInfoMember.setProjectId(infoId);
            List<GatherInfoMember> gatherInfoMembers = gatherInfoMemberService.list(gatherInfoMember);
            List<Map<String, Object>> memberInfos = gatherInfoMemberService.webListPage(memberInfo, Maps.newHashMap(), null);
            List<String> memberIds = new ArrayList<String>();
            memberIds.add(gatherInfoProject.getCreateBy());
            String circleId = circleBizService.createCircleBusinessGatherinfo(infoId, gatherInfoProject, type);
            circleMemberBizService.circleMemberManageGatherinfo(gatherInfoMembers, circleId, memberIds, RealmUtils.getCurrentUser().getId());
            //ExecutorService transferThreadPool = Executors.newFixedThreadPool(2);
            //transferThreadPool.execute();
            gatherInfoGroup.setProjectId(infoId);
            List<GatherInfoGroup> groups = gatherInfoGroupService.list(gatherInfoGroup);
            for (GatherInfoGroup gi : groups) {
                CircleTag circleTag = new CircleTag();
                circleTag.setCircle(circleId);
                circleTag.setTagName(gi.getGroupName());
                try {
                    int sort = Integer.parseInt(gi.getGroupNo());
                    circleTag.setSort(sort);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                List<CircleTag> circleTagList = circleTagService.list(circleTag);
                if (circleTagList.size() == 0) {
                    circleTagService.insert(circleTag);
                }
            }
            for (Map<String, Object> GMember : memberInfos) {
                CircleTag circleTag = new CircleTag();
                String id = (String) GMember.get("memberId");
                String gropName = (String) GMember.get("groupName");
                if (gropName != "" && null != gropName) {
                    CircleMemberTag circleMemberTag = new CircleMemberTag();
                    circleMemberTag.setCircle(circleId);
                    circleMemberTag.setMember(id);
                    circleTag.setCircle(circleId);
                    circleTag.setTagName(gropName);
                    List<CircleMemberTag> cmList = circleMemberTagService.list(circleMemberTag);
                    if (cmList.size() == 0) {
                        List<CircleTag> ct = circleTagService.list(circleTag);
                        if (ct.size() > 0) {
                            circleMemberTag.setTag(ct.get(0).getId());
                            circleMemberTagService.insert(circleMemberTag);
                        }
                    }
                }
            }

            circleBizNewService.uploadQrCode(gatherInfoProject.getCreateBy(), circleId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("圈子保存异常", e);
            return AjaxResult.error("圈子保存异常");
        }
    }

    /**
     * 新增/编辑表单
     *
     * @param id
     * @return
     */
    @RequestMapping("toForm")
    public ModelAndView toForm(String id) {
        ModelAndView mv = new ModelAndView("gatherInfo/projectForm");
        if (StringUtils.isNotEmpty(id)) {
            GatherInfoProject project = gatherInfoProjectService.get(id);

            // 基本信息描述
            // if (StringUtils.isNotEmpty(project.getBaseInfoDesc())) {
            // project.setBaseInfoDesc(StringEscapeUtils.unescapeHtml4(project.getBaseInfoDesc()));
            // }
            // 行程信息描述
            // if (StringUtils.isNotEmpty(project.getItineraryInfoDesc())) {
            // project.setItineraryInfoDesc(StringEscapeUtils.unescapeHtml4(project.getItineraryInfoDesc()));
            // }
            // 保险信息描述
            // if (StringUtils.isNotEmpty(project.getInsuranceInfoDesc())) {
            // project.setInsuranceInfoDesc(StringEscapeUtils.unescapeHtml4(project.getInsuranceInfoDesc()));
            // }

            mv.addObject("project", project);
        }
        return mv;
    }

    /**
     * 保存
     *
     * @param project
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public AjaxResult save(GatherInfoProject project) {

        // 基本信息描述
        // if (StringUtils.isNotEmpty(project.getBaseInfoDesc())) {
        // String baseInfo =
        // StringEscapeUtils.escapeHtml4(project.getBaseInfoDesc().trim());
        // project.setBaseInfoDesc(baseInfo);
        // }
        // 行程信息描述
        // if (StringUtils.isNotEmpty(project.getItineraryInfoDesc())) {
        // String itineraryInfo =
        // StringEscapeUtils.escapeHtml4(project.getItineraryInfoDesc().trim());
        // project.setItineraryInfoDesc(itineraryInfo);
        // }
        // 保险信息描述
        // if (StringUtils.isNotEmpty(project.getInsuranceInfoDesc())) {
        // String insuranceInfo =
        // StringEscapeUtils.escapeHtml4(project.getInsuranceInfoDesc().trim());
        // project.setInsuranceInfoDesc(insuranceInfo);
        // }
        try {
            String memberId = Strings.isNullOrEmpty(project.getCreateBy()) ? RealmUtils.getCurrentUser().getId() : project.getCreateBy();
            if (StringUtils.isEmpty(project.getId())) {
                project.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                project.setCreateBy(memberId);
                project.setUpdateBy(memberId);
                gatherInfoProjectService.insert(project);
            } else {
                GatherInfoProject t = gatherInfoProjectService.get(project.getId());
                MyBeanUtils.copyBeanNotNull2Bean(project, t);
                gatherInfoProjectService.update(t);
                memberId = t.getCreateBy();
            }

            itineraryBizService.uploadQrCode(memberId, project.getId());

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存人员信息收集项目异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @param id 项目编号
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        List<GatherInfoMember> memberInfoForms = gatherInfoMemberService.findByProject(id);
        if (memberInfoForms.size() > 0) {
            return AjaxResult.error("该项目下已有收集人员信息，不能删除");
        }
        List<GatherInfoGroup> gatherInfoGroups = gatherInfoGroupService.list(new GatherInfoGroup(id));
        if (gatherInfoGroups.size() > 0) {
            return AjaxResult.error("该项目下已有小组，不能删除");
        }
        boolean result = itineraryBizService.deleteProjectBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 同步生成赛事项目
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("syncCompetition")
    public AjaxResult syncCompetition(String id, String type) {
        try {
            GatherInfoProject gProject = gatherInfoProjectService.get(id);
            String cProjectId = "";
            String currentId = RealmUtils.getCurrentUser().getId();
            CompetitionBusiness cBusiness = competitionBusinessService.findByBusinessId(id, type);
            if (cBusiness == null) {
                cBusiness = new CompetitionBusiness();
                cBusiness.setBusinessId(id);
                cBusiness.setType(type);
                cBusiness.setCreateBy(currentId);
                cBusiness.setUpdateBy(currentId);
                String competitionId = competitionProjectBizService.createCompetition(gProject.getTitle(), gProject.getCreateBy());
                cBusiness.setCompetitionId(competitionId);
                competitionBusinessService.insert(cBusiness);

                cProjectId = competitionId;
            } else {
                String competitionId = cBusiness.getCompetitionId();
                CompetitionProject cProject = competitionProjectService.get(competitionId);
                if (cProject == null) {
                    competitionId = competitionProjectBizService.createCompetition(gProject.getTitle(), gProject.getCreateBy());
                    cBusiness.setCompetitionId(competitionId);
                    competitionBusinessService.update(cBusiness);

                    cProjectId = competitionId;
                } else {
                    cProject.setTitle(gProject.getTitle());
                    competitionProjectService.update(cProject);

                    cProjectId = cProject.getId();
                }
            }

            competitionProjectBizService.insertCompetitionMember(cProjectId, gProject.getId(), gProject.getCreateBy());

            try {
                String memberId = gProject.getCreateBy();
                String filePath = fileBizService.getUploadCIPath(memberId, "competition");
                String content = "competition/all_person_rank.html?projectId=" + gProject.getId();
                fileBizService.uploadCloudOut(gProject.getId(), filePath, content, memberId);
            } catch (Exception e) {
                logger.error("生成赛事成绩项目二维码异常", e);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成赛事项目异常", e);
            return AjaxResult.error("生成赛事项目异常");
        }
    }

    @ResponseBody
    @RequestMapping("initQrCode")
    public AjaxResult initQrCode() {
        List<GatherInfoProject> memberInfoProjects = gatherInfoProjectService.list(new GatherInfoProject());
        for (GatherInfoProject project : memberInfoProjects) {
            String memberId = project.getCreateBy();

            String filePath = fileBizService.getUploadCIPath(memberId, "gatherInfo");

            String baseFileName = "base_" + project.getId();
            String path = memberId + "/gatherInfo/base/";
            String baseContent = "gather_info/base_info.html?projectId=" + project.getId();
            fileBizService.uploadCloudOut(baseFileName, filePath, path, project.getId(), baseContent, memberId);

            String insuranceFileName = "insurance_" + project.getId();
            path = memberId + "/gatherInfo/insurance/";
            String insuranceContent = "gather_info/insurance_info.html?projectId=" + project.getId();
            fileBizService.uploadCloudOut(insuranceFileName, filePath, path, project.getId(), insuranceContent, memberId);

            String itineraryFileName = "itinerary_" + project.getId();
            path = memberId + "/gatherInfo/itinerary/";
            String itineraryContent = "gather_info/itinerary_info.html?projectId=" + project.getId();
            fileBizService.uploadCloudOut(itineraryFileName, filePath, path, project.getId(), itineraryContent, memberId);
        }
        return AjaxResult.success();
    }
}
